package com.newtouch.cq.security.config.handle;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.json.JSONUtil;
import com.newtouch.cq.lang.result.MccObjectResult;
import com.newtouch.cq.lang.user.BaseUserDetails;
import com.newtouch.cq.security.token.TokenCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Alex
 * @Description 登录成功后的处理
 * @time 2021/8/25 9:51
 */
@Component
public class LoginSuccessHandle extends SavedRequestAwareAuthenticationSuccessHandler {

    @Autowired
    protected TokenCache<? extends UserDetails> tokenCache;

    private RequestCache requestCache = new HttpSessionRequestCache();


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        if (null != authentication) {
            BaseUserDetails user = (BaseUserDetails) authentication.getPrincipal();
            String userKey = user.getUserKey();
            String tokenKey = user.getTokenKey();
            user.setPassword(null);
            tokenCache.saveToken(userKey, tokenKey, user);
        }

            SavedRequest savedRequest = this.requestCache.getRequest(request, response);
        if (savedRequest != null) {
            super.onAuthenticationSuccess(request, response, authentication);
        } else {
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(200);
            response.getWriter().write(JSONUtil.toJsonStr(MccObjectResult.success(authentication)));
        }
    }
}
